from django.db import models
from imagetools.scaledcopies import ScaledCopies
import Image
import os,zipfile
from django.conf import settings

def unzip_file_into_dir(file, dir):
    os.mkdir(dir, 0777)
    zfobj = zipfile.ZipFile(file)
    for name in zfobj.namelist():
        if name.endswith('/'):
            os.mkdir(os.path.join(dir, name))
        else:
            outfile = open(os.path.join(dir, name), 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()



class Album(models.Model):
    """
       Organizes photos into groups - 
        this model should at some point support a full tree
        i.e: albumx.albumy.photo / etc.
    """
    name = models.CharField(max_length=80)
    caption = models.TextField()
    thumb = models.ImageField(upload_to='gallery_images/',max_length=1000,blank=True)
    photos = models.FileField(upload_to='gallery_images/tmp/',max_length=1000,blank=True,
                               verbose_name='Batch upload for this album (.zip)')
    
    weight = models.IntegerField(blank=True, null=True)
    
    def __unicode__(self):
        return self.name 
    
    def add_photos_from_zipfile(self,file,dir):
            
        os.mkdir(dir, 0777)
        zfobj = zipfile.ZipFile(file)
       
        for name in zfobj.namelist():
            if not name.find("__MACOS"):
                continue
            if name.endswith('/'):
                os.mkdir(os.path.join(dir, name))
            else:
                outfile = open(os.path.join(dir, name), 'wb')
                outfile.write(zfobj.read(name))
                outfile.close()
            
            if name.endswith("jpeg") or name.endswith("png") or name.endswith("jpg") \
            or name.endswith("JPEG") or name.endswith("PNG") or name.endswith("JPG"):
                photo = Photo()
                photo.title=name.replace("/","").replace(" ","").replace(",","").\
                    replace("__MACOSX","").replace(".","").replace("_","").\
                    replace("jpg","").replace("JPEG","").replace("png","").replace("PNG","")
                photo.photo = 'gallery_images/'+self.name+"/"+name
                photo.album_id = self.id
                photo.caption = photo.title
                try:
                    photo.save()
                    photo.photo.url = "/media/gallery_images/"+name
                except:
                  print "didn't save: dir+name:"+dir+"/"+name  
    def save(self):
        super(Album,self).save()
        #so we've reached this point.  Now see if we got something from the photos thing
        #try:
        unzip_dir = settings.MEDIA_ROOT+'/gallery_images/'+self.name
                
        if not os.path.exists(unzip_dir):
            self.add_photos_from_zipfile(self.photos.path,unzip_dir)
        else:
            print 'that directory already existed.  should delete it.'
            os.rmdir(unzip_dir)
            self.add_photos_from_zipfile(self.photos.path,unzip_dir)

        #except:
        #    pass
        self.images = ScaledCopies(self.thumb,scales=[400]).saveCopies()
    
    class Meta:
        ordering = ('weight','name')
        
class Photo(models.Model):
    """
        A photo object stores the location of the file on disk.
        It should at some point have some validation built in to flag a warning
        if the file is no longer present or has changed.
    """
    title = models.CharField(max_length=80)
    photo = models.ImageField(upload_to='gallery_images',max_length=1000) 
    caption = models.TextField(blank=True,null=True)
    album = models.ForeignKey(Album)
    weight = models.IntegerField(blank=True,null=True)
    purchaseURL = models.URLField(blank = True)
    images = ScaledCopies(photo)
    #width = models.DecimalField(decimal_places=4,max_digits=4)
    #height = models.DecimalField(decimal_places=4,max_digits=4)
    
    @property
    def preview_url(self):
        """
            just a shortcut to the proper image for generated for the gallery
        """
        return self.photo.url+"400.jpeg"
    
    def save(self):
        super(Photo,self).save()
        self.images.saveCopies(photo=self.photo)
            
    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ('weight','title')

